<template>
	<view class="search-box">
		<uni-search-bar :cancelButton="none" :focus="true" :radius="100" @confirm="search"
			@input="input"></uni-search-bar>
	</view>
	<view v-if="searchResult.length === 0" class="history-box">
		<view  class="history-title">
			<text>搜索历史</text>
			<uni-icons @click="clearHistory" type="trash" size="25"></uni-icons>
		</view>
		<view class="history-list">
			<uni-tag size="normal" @click="goToShopList(item)" v-for="(item,i) in history" :text="item" :key="i"></uni-tag>
		</view>
	</view>
	<view v-if="searchResult.length !== 0" class="search-list">
		<view @click="getToDetials(item.goodsId)" class="search-item" v-for="(item,i) in searchResult" :key="i">
			<view class="goods-name">{{item.goodsName}}</view>
			<uni-icons type="arrowright" size="16"></uni-icons>
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				timer: null,
				searchResult: [],
				historyData: [],
				kw: ''
			};
		},
		computed:{
			history(){
				return [...this.historyData].reverse()
			}
		},
		onLoad() {
			this.historyData = JSON.parse(uni.getStorageSync('kw')||'[]')
		},
		methods: {
			goToShopList(item){
				uni.navigateTo({
					url:'/subpackage/goods/goods?query='+item
				})
			},
			clearHistory(){
				this.historyData = [],
				uni.setStorageSync('kw','[]')
			},
			search(){console.log("search")},
			getToDetials(good_id) {
				console.log(good_id)
				uni.navigateTo({
					url: '/subpackage/shops/shops?goodsId=' + good_id
				})
			},
			input(e) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.kw = e
					console.log(this.kw, e)
					this.getSearchList()
				}, 500)
			},
			async getSearchList() {
				if (this.kw.length === '') {
					this.searchResult = []
					return
				}
				let set = new Set(this.historyData)
				set.add(this.kw)
				this.historyData = Array.from(set)
				uni.setStorageSync('kw',JSON.stringify(this.historyData))
				const {
					data
				} = await uni.$http.get('http://192.168.1.11:8080/get/getgoodslist?query=' + this.kw)
				this.searchResult = data.result
			}
		}
	}
</script>

<style lang="scss">
	.search-box {
		position: sticky;
		z-index: 999;
		top: 0px;
	}
	.history-box{
		padding: 0 5px;
		.history-title{
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 40px;
			border-bottom: 1px solid #efefef;
		}
		.history-list{
			display: flex;
			flex-wrap: wrap;
			justify-content: left;
			uni-tag{
				margin-left: 5px;
				margin-top: 5px;
			}
		}
	}
	.search-list {
		padding: 0 10px;

		.search-item {
			font-size: 14px;
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.goods-name {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}

	}
</style>